package com.api.weavernorth.createtrip;


import com.api.weavernorth.EditHrmMessageController;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.workflow.webservices.*;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.text.SimpleDateFormat;

import java.util.Date;


/**
 * 汇联易会创建OA出差流程,当申请时,创建OA出差申请流程,变更时,把上次的流程id传入OA,并创建出差变更流程
 */

@Path("/OA")
public class CreateTripWorkflow extends HttpServlet {
    private static Log log = org.apache.commons.logging.LogFactory.getLog(CreateTripWorkflow.class.getName());

    @POST
    @Path("/editMess")
    @Produces(MediaType.APPLICATION_JSON)
    public JSONObject editHrmmess(@Context HttpServletRequest httpservletrequest, @Context HttpServletResponse httpservletresponse, String userMess)
            throws ServletException, IOException {
        //返回信息
        EditHrmMessageController editHrmMessageController = new EditHrmMessageController();
        JSONObject jsonObject = editHrmMessageController.editmess(userMess);
        return jsonObject;
    }

    @POST
    @Path("/createTrip")
    @Produces(MediaType.APPLICATION_JSON)
    public String createTripWorkflow(@Context HttpServletRequest request, @Context HttpServletResponse response, JSONObject jsonObject) {
        //返回json
        JSONObject jsonReturn = new JSONObject();
        //基础类
        BaseBean bb = new BaseBean();
        //异构系统传入的参数
        log.info("异构系统传入的数据:" + jsonObject.toString());
        //通过JSONObject.toBean()方法进行对象间的转换
        TripVo trip = (TripVo) JSONObject.toBean(jsonObject, TripVo.class);
        //人员编码
        String strWorkcode = Util.null2String(trip.getWorkCode());
        //订单编号
        String strOrderNo=Util.null2String(trip.getOrderno());
        //得到人员id
        String strUserid = getId(strWorkcode, "hrmresource", "workcode");
        if ("".equals(strUserid)) {
            jsonReturn.put("requestid", "-9");
            jsonReturn.put("msg", "人员编码未在OA中找到");
            return jsonReturn.toString();
        }
        //部门编码
        String strDepartcode = Util.null2String(trip.getDepartmentCode());
        //得到部门id
        String strDepartId = getId(strDepartcode, "hrmdepartment", "departmentcode");
        //开始日期
        String strBeginDate = Util.null2String(trip.getBeginDate());
        //开始时间
        String strBeginTime = Util.null2String(bb.getPropValue("tripMess", "beginTime"));
        //结束日期
        String strEndDate = Util.null2String(trip.getEndDate());
        //结束时间
        String strEndTime = Util.null2String(bb.getPropValue("tripMess", "endTime"));
        //时长
        String strDuration = getDays(strBeginDate, strEndDate);
        log.info("当前时长:" + strDuration);

        //同行人的workcode
        String strCompanion = Util.null2String(trip.getCompanion());
        String strCompanionId = getId(strCompanion, "hrmresource", "workcode");

        //类型 0:变更,1:撤销,2:出差申请
        String strType = Util.null2String(trip.getType());
        //如果变更的话,同行人每个都要创建一条流程
        String strCreater = strUserid;
        if ("0".equals(strType)) {
            strCreater = strCreater + "," + strCompanionId;
        }


//        String[] strUserArr = strCreater.split(",");
//        for (int i = 0; i < strUserArr.length; i++) {
            //开始创建流程
            WorkflowRequestTableField[] wrti = new WorkflowRequestTableField[20];
            WorkflowMainTableInfo wmi = new WorkflowMainTableInfo();

            WorkflowRequestInfo wri = new WorkflowRequestInfo();

            wrti[0] = new WorkflowRequestTableField();
            wrti[0].setFieldName("resourceId");
            wrti[0].setFieldValue(Util.null2String(strUserid));
            wrti[0].setView(true);
            wrti[0].setEdit(true);
            wrti[0].setFieldOrder(0);
            wrti[0].setMand(false);
            if ("2".equals(strType)) {
                wrti[1] = new WorkflowRequestTableField();
                wrti[1].setFieldName("departmentId");
                wrti[1].setFieldValue(strDepartId);
                wrti[1].setView(true);
                wrti[1].setEdit(true);
                wrti[1].setFieldOrder(0);
                wrti[1].setMand(false);

                wrti[2] = new WorkflowRequestTableField();
                wrti[2].setFieldName("fromDate");
                wrti[2].setFieldValue(strBeginDate);
                wrti[2].setView(true);
                wrti[2].setEdit(true);
                wrti[2].setFieldOrder(0);
                wrti[2].setMand(false);

                wrti[3] = new WorkflowRequestTableField();
                wrti[3].setFieldName("fromTime");
                wrti[3].setFieldValue(strBeginTime);
                wrti[3].setView(true);
                wrti[3].setEdit(true);
                wrti[3].setFieldOrder(0);
                wrti[3].setMand(false);

                wrti[4] = new WorkflowRequestTableField();
                wrti[4].setFieldName("toDate");
                wrti[4].setFieldValue(strEndDate);
                wrti[4].setView(true);
                wrti[4].setEdit(true);
                wrti[4].setFieldOrder(0);
                wrti[4].setMand(false);

                wrti[5] = new WorkflowRequestTableField();
                wrti[5].setFieldName("toTime");
                wrti[5].setFieldValue(strEndTime);
                wrti[5].setView(true);
                wrti[5].setEdit(true);
                wrti[5].setFieldOrder(0);
                wrti[5].setMand(false);

                wrti[6] = new WorkflowRequestTableField();
                wrti[6].setFieldName("duration");
                wrti[6].setFieldValue(strDuration);
                wrti[6].setView(true);
                wrti[6].setEdit(true);
                wrti[6].setFieldOrder(0);
                wrti[6].setMand(false);

//                wrti[7] = new WorkflowRequestTableField();
//                wrti[7].setFieldName("companion");
//                wrti[7].setFieldValue(strCompanionId);
//                wrti[7].setView(true);
//                wrti[7].setEdit(true);
//                wrti[7].setFieldOrder(0);
//                wrti[7].setMand(false);

                //装填主表信息
                WorkflowRequestTableRecord[] wrtri = new WorkflowRequestTableRecord[1];
                wrtri[0] = new WorkflowRequestTableRecord();
                wrtri[0].setWorkflowRequestTableFields(wrti);

                wmi.setRequestRecords(wrtri);
            } else {
                //创建出差变更流程
                //上次流程id
                String strRequestid = Util.null2String(trip.getRequestid());


                wrti[1] = new WorkflowRequestTableField();
                wrti[1].setFieldName("changerequestid");
                wrti[1].setFieldValue(strRequestid);
                wrti[1].setView(true);
                wrti[1].setEdit(true);
                wrti[1].setFieldOrder(0);
                wrti[1].setMand(false);

                wrti[2] = new WorkflowRequestTableField();
                wrti[2].setFieldName("changetype");
                wrti[2].setFieldValue(strType);
                wrti[2].setView(true);
                wrti[2].setEdit(true);
                wrti[2].setFieldOrder(0);
                wrti[2].setMand(false);

                //装填主表信息
                WorkflowRequestTableRecord[] wrtri = new WorkflowRequestTableRecord[1];
                wrtri[0] = new WorkflowRequestTableRecord();
                wrtri[0].setWorkflowRequestTableFields(wrti);

                wmi.setRequestRecords(wrtri);
                //明细表
                //查找此流程的信息
                JSONObject jsonRequest = getTripMess(strRequestid);
                jsonObject.put("beginDate", strBeginDate);
                jsonObject.put("beginTime", strBeginTime);
                jsonObject.put("endDate", strEndDate);
                jsonObject.put("endTime", strEndTime);
                jsonObject.put("duration", strDuration);


                WorkflowDetailTableInfo wdti[] = new WorkflowDetailTableInfo[1];
                wrtri = new WorkflowRequestTableRecord[1];
                wrti = new WorkflowRequestTableField[20];
                wrti[0] = new WorkflowRequestTableField();
                wrti[0].setFieldName("detail_attendancefromDate");
                wrti[0].setFieldValue(jsonRequest.getString("beginDate"));
                wrti[0].setView(true);
                wrti[0].setEdit(true);


                wrti[1] = new WorkflowRequestTableField();
                wrti[1].setFieldName("detail_attendancefromTime");
                wrti[1].setFieldValue(jsonRequest.getString("beginTime"));
                wrti[1].setView(true);
                wrti[1].setEdit(true);

                wrti[2] = new WorkflowRequestTableField();
                wrti[2].setFieldName("detail_attendancetoDate");
                wrti[2].setFieldValue(jsonRequest.getString("endDate"));
                wrti[2].setView(true);
                wrti[2].setEdit(true);

                wrti[3] = new WorkflowRequestTableField();
                wrti[3].setFieldName("detail_attendancetoTime");
                wrti[3].setFieldValue(jsonRequest.getString("endTime"));
                wrti[3].setView(true);
                wrti[3].setEdit(true);

                wrti[4] = new WorkflowRequestTableField();
                wrti[4].setFieldName("detail_attendanceduration");
                wrti[4].setFieldValue(jsonRequest.getString("duration"));
                wrti[4].setView(true);
                wrti[4].setEdit(true);

                wrti[5] = new WorkflowRequestTableField();
                wrti[5].setFieldName("detail_changefromDate");
                wrti[5].setFieldValue(strBeginDate);
                wrti[5].setView(true);
                wrti[5].setEdit(true);

                wrti[6] = new WorkflowRequestTableField();
                wrti[6].setFieldName("detail_changefromTime");
                wrti[6].setFieldValue(strBeginTime);
                wrti[6].setView(true);
                wrti[6].setEdit(true);

                wrti[7] = new WorkflowRequestTableField();
                wrti[7].setFieldName("detail_changetoDate");
                wrti[7].setFieldValue(strEndDate);
                wrti[7].setView(true);
                wrti[7].setEdit(true);

                wrti[8] = new WorkflowRequestTableField();
                wrti[8].setFieldName("detail_changetoTime");
                wrti[8].setFieldValue(strEndTime);
                wrti[8].setView(true);
                wrti[8].setEdit(true);

                wrti[9] = new WorkflowRequestTableField();
                wrti[9].setFieldName("detail_changeduration");
                wrti[9].setFieldValue(strDuration);
                wrti[9].setView(true);
                wrti[9].setEdit(true);
                wrtri[0] = new WorkflowRequestTableRecord();
                wrtri[0].setWorkflowRequestTableFields(wrti);

                wdti[0] = new WorkflowDetailTableInfo();
                wdti[0].setWorkflowRequestTableRecords(wrtri);
                //明细表数据
                wri.setWorkflowDetailTableInfos(wdti);
            }



            //基本信息
            WorkflowBaseInfo wbi = new WorkflowBaseInfo();
            //流程workflowid
            if ("2".equals(strType)) {
                wbi.setWorkflowId(bb.getPropValue("tripMess", "tripWorkflow"));
                //请求的名称
                wri.setRequestName("汇联易出差申请流程"+strOrderNo);
            } else {
                wbi.setWorkflowId(bb.getPropValue("tripMess", "tripChangeWorkflow"));
                //请求的名称
                wri.setRequestName("汇联易考勤变更流程"+strOrderNo);
            }

            //创建人
            wri.setCreatorId(strUserid);
            //紧急程度
            wri.setRequestLevel("0");

            //停留在待办
            //wri.setIsnextflow("0");

            //主表数据
            wri.setWorkflowMainTableInfo(wmi);
            wri.setWorkflowBaseInfo(wbi);

            WorkflowServiceImpl wfsi = new WorkflowServiceImpl();

            String requestid = wfsi.doCreateWorkflowRequest(wri, Integer.parseInt(strUserid));
            log.info("批量生成流程返回值==" + requestid);
            if (strUserid.equals(strUserid)) {
                if (!"".equals(requestid) && Integer.parseInt(requestid) > 0) {
                    jsonReturn.put("requestid", requestid);
                    jsonReturn.put("msg", "流程创建成功");
                } else {
                    jsonReturn.put("requestid", requestid);
                    jsonReturn.put("msg", "流程创建失败");
                }
            }
//        }
        return jsonReturn.toString();

    }


    /**
     * 由编码查询人员或部门的id
     *
     * @
     */
    public String getId(String strCode, String strTable, String strField) {
        //返回值
        String strReturn = "";
        //数据库连接
        RecordSet rs = new RecordSet();
        String strNewCode = "";
        //处理多个数据传in问题
        if (!"".equals(strCode)) {
            String[] arrCode = (strCode.split(","));
            for (int i = 0; i < arrCode.length; i++) {
                strNewCode = strNewCode + "'" + arrCode[i] + "',";

            }

            strNewCode = strNewCode.substring(0, strNewCode.length() - 1);
        }
        String strSql = "select id from " + strTable + " where " + strField + " in(" + strNewCode + ")";

        if ("hrmresource".equals(strTable)) {
            strSql = strSql + " and (accounttype is null or accounttype='0')";
        }
        log.info("查询id:" + strSql + ",code:" + strNewCode);
        rs.executeQuery(strSql);
        while (rs.next()) {
            strReturn = strReturn + Util.null2String(rs.getString("id")) + ",";
        }
        if (!"".equals(strReturn)) {
            strReturn = strReturn.substring(0, strReturn.length() - 1);
        }
        log.info("返回的值:" + strReturn);
        return strReturn;
    }

    /**
     * 根据requestid查询信息
     */

    public JSONObject getTripMess(String strRequestid) {
        //返回值
        JSONObject jsonObject = new JSONObject();
        //基础类
        BaseBean bb = new BaseBean();
        //数据库操作
        RecordSet rs = new RecordSet();
        //流程分类id
        String strWorkflowid = "";
        //开始日期
        String strBeginDate = "";
        //开始时间
        String strBeginTime = "";
        //结束日期
        String strEndDate = "";
        //结束时间
        String strEndTime = "";
        //时长
        String strDuration = "";

        //由requestid得到workflowid
        String strFlowSql = "select workflowid from workflow_requestbase where requestid=?";
        rs.executeQuery(strFlowSql, strRequestid);
        if (rs.next()) {
            strWorkflowid = Util.null2String(rs.getString("workflowid"));
        }
        log.info("当前流程的分类id:" + strWorkflowid);
        //出差流程id
        String tripWorkflow = Util.null2String(bb.getPropValue("tripMess", "tripWorkflow"));
        log.info("出差流程的分类id:" + tripWorkflow);
        //出差变更流程id
        String tripChangeWorkflow = Util.null2String(bb.getPropValue("tripMess", "tripChangeWorkflow"));
        log.info("出差变更流程的分类id:" + tripWorkflow);

        //如果流程为出差流程
        if (strWorkflowid.equals(tripWorkflow)) {
            //出差流程表
            String tripTable = Util.null2String(bb.getPropValue("tripMess", "tripTable"));
            //查询出差信息
            String tripSql = "select fromDate,fromTime,toDate, toTime,duration from " + tripTable + " where requestid=?";
            rs.executeQuery(tripSql, strRequestid);
            if (rs.next()) {
                strBeginDate = Util.null2String(rs.getString("fromDate"));
                strBeginTime = Util.null2String(rs.getString("fromTime"));
                strEndDate = Util.null2String(rs.getString("toDate"));
                strEndTime = Util.null2String(rs.getString("toTime"));
                strDuration = Util.null2String(rs.getString("duration"));
            }

        } else if (strWorkflowid.equals(tripChangeWorkflow)) {
            //出差流程表
            String tripTable = Util.null2String(bb.getPropValue("tripMess", "tripChangeTable"));
            //查询出差信息
            String tripSql = "select * from " + tripTable + " fm," + tripTable + "_dt1  fmd where fm.id=fmd.mainid and fm.requestid=?";
            rs.executeQuery(tripSql, strRequestid);
            if (rs.next()) {
                strBeginDate = Util.null2String(rs.getString("detail_changefromDate"));
                strBeginTime = Util.null2String(rs.getString("detail_changefromTime"));
                strEndDate = Util.null2String(rs.getString("detail_changetoDate"));
                strEndTime = Util.null2String(rs.getString("detail_changetoTime"));
                strDuration = Util.null2String(rs.getString("detail_changeduration"));
            }

        }
        jsonObject.put("beginDate", strBeginDate);
        jsonObject.put("beginTime", strBeginTime);
        jsonObject.put("endDate", strEndDate);
        jsonObject.put("endTime", strEndTime);
        jsonObject.put("duration", strDuration);


        return jsonObject;

    }

    /**
     * 计算开始日期结束日期相差天数
     */
    public String getDays(String strBeginDate, String strEndDate) {
        //设置转换的日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        long betweenDate = 0L;
        try {
            //开始时间
            Date startDate = sdf.parse(strBeginDate);
            log.info("开始时间:" + startDate.getTime());
            //结束时间
            Date endDate = sdf.parse(strEndDate);
            log.info("结束时间:" + endDate.getTime());
            //得到相差的天数 betweenDate
            betweenDate = (endDate.getTime() - startDate.getTime()) / (60 * 60 * 24 * 1000) + 1;
            log.info("相差天数:" + betweenDate);
        } catch (Exception e) {
            e.printStackTrace();
        }


        return String.valueOf(betweenDate);

    }


}